package com.gzhryc.net_marketing.cloud.micro.api.jetty;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.PatternHelper;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.cloud.micro.api.MicroConstants;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.shared_device.oem.code.member.LoginMember;
import com.gzhryc.shared_device.oem.code.member.LoginMemberSessionManager;

public class SecurityFilter implements Filter{
	
	static Logger log = Logger.getLogger(SecurityFilter.class);
	
	private static Pattern _Pat = Pattern.compile("^/market/v1(/.*)$");
	private static Pattern _Pat_Cloud_API = Pattern.compile("^/market/cloud_api/.*$");		//云接口
	private static Pattern _Pat_PayCall = Pattern.compile("^/paycall/.*$");
	
	PatternHelper patHelper;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		patHelper = new PatternHelper();
		patHelper.addExcludePattern(Pattern.compile("^/goods/list.data$"));
		patHelper.addExcludePattern(Pattern.compile("^/goods/info.data$"));
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		String url = httpRequest.getRequestURI();
		
		//支付回调
		if(_Pat_PayCall.matcher(url).find()){
			httpRequest.setAttribute("uri", url);
			chain.doFilter(httpRequest, httpResponse);
			return;
		}
		
		//云API回调
		if(_Pat_Cloud_API.matcher(url).find()){
			httpRequest.setAttribute("uri", url);
			chain.doFilter(httpRequest, httpResponse);
			return;
		}
		
		String userAgent = httpRequest.getHeader("User-Agent");
		if (MicroConstants.isDebug() == 0) {
			if (!WebUtils.isMobileOrTablet(httpRequest)) {
				log.error("访问阻止：{{0}}，userAgent = {{1}}",url,userAgent);
				AjaxResult result = new AjaxResult(DtoConstants.NOT_POWER, "请使用手机端");
				WebUtils.toJson(httpResponse, result);
				return;
			}
		}
		
		log.info("登陆路径：{{0}}", url);

		Matcher mat = _Pat.matcher(url);
		if (mat.find()) {
			String uri = mat.group(1);
			log.info("截取路径：{{0}}", uri);
			if (patHelper.isExclude(uri)) {
				httpRequest.setAttribute("uri", uri);
				chain.doFilter(httpRequest, httpResponse);
				return;
			}else if (uri.endsWith(".do") || uri.endsWith(".data")) {
				String loginToken = httpRequest.getHeader("authorization");
				if (StringUtils.isNotBlank(loginToken)) {
					LoginMember loginMember = LoginMemberSessionManager.self().getMemberSession(loginToken);
					if (loginMember != null) {
						httpRequest.setAttribute("uri", uri);
						httpRequest.setAttribute(MicroConstants.ATTR_LOGIN_MEMBER, loginMember);
						chain.doFilter(httpRequest, httpResponse);
						return;
					}else {
						log.error("未获取登陆会员，loginToken = {{0}}", loginToken);
					}
				}
			}
		}

		AjaxResult result = new AjaxResult(DtoConstants.LOGIN_OVERDUE, "登录过期，请重新登录");
		WebUtils.toJson(httpResponse, result);
	}

	@Override
	public void destroy() {}
}
